package com.sojson.serversocket.util;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import com.sojson.serversocket.util.bean.ServerSocketConnect;
import com.sojson.serversocket.util.enums.EElectricType;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

/**
 * ServerSocket连接池工具类
 *
 * @author liu
 * @date 2024-05-31
 */
@Slf4j
public class ServerSocketPoolUtil {

    /** 参数名 */
    public static final String ID_KEY = "ID";
    public static final String TYPE_KEY = "TYPE";
    public static final String ADDR_KEY = "ADDR";
    public static final String DATA_KEY = "DATA";
    public static final String ADDRS_KEY = "ADDRS";
    public static final String DATA_TIME_KEY = "DATA_TIME";
    private static ConcurrentMap<String, ServerSocketConnect> map = new ConcurrentHashMap<>(1000);

    public static void put(EElectricType type, String tokenId, ChannelHandlerContext ctx) {
        ServerSocketConnect connect = map.get(tokenId);
        if (connect == null) {
            connect = new ServerSocketConnect();
            map.put(tokenId, connect);
        }
        connect.setCtx(ctx);

        if (ctx == null) {
            return;
        }

        log.info(
            new StringBuilder().append("====== ServerSocketOnOpen: ").append(tokenId).append(" ======").toString());
        ctx.channel().attr(AttributeKey.valueOf(TYPE_KEY)).set(type);
        ctx.channel().attr(AttributeKey.valueOf(ADDR_KEY)).set(tokenId);
        ctx.channel().attr(AttributeKey.valueOf(DATA_KEY)).set("");
    }

    public static ServerSocketConnect get(String tokenId) {
        return map.get(tokenId);
    }

    public static void remove(String tokenId) {
        log.info(
            new StringBuilder().append("====== ServerSocketOnClose: ").append(tokenId).append(" ======").toString());
        ServerSocketConnect connect = map.get(tokenId);
        if (connect != null) {
            connect.setCtx(null);
        }
    }

    public static void removeConnect(String tokenId) {
        log.info(
            new StringBuilder().append("====== ServerSocketOnClose: ").append(tokenId).append(" ======").toString());
        map.put(tokenId, null);
    }

    public static Collection<ServerSocketConnect> getValues() {
        return map.values();
    }

}